<template>
  <div class="h-full flex flex-col space-y-6 overflow-y-auto">
    <!-- Header -->
    <div class="flex-shrink-0">
      <h1 class="text-2xl font-bold text-gray-900 dark:text-gray-100">设置</h1>
      <p class="text-gray-600 dark:text-gray-400 mt-1">
        个性化您的系统体验
      </p>
    </div>

    <!-- Settings sections -->
    <div class="flex-1 grid grid-cols-1 lg:grid-cols-3 gap-8 min-h-0">
      <!-- Settings navigation -->
      <div class="lg:col-span-1">
        <nav class="space-y-1">
          <button
            v-for="section in sections"
            :key="section.id"
            @click="activeSection = section.id"
            :class="[
              'w-full flex items-center px-3 py-2 text-sm font-medium rounded-lg text-left transition-all duration-200',
              {
                'bg-primary-100 dark:bg-primary-900/20 text-primary-700 dark:text-primary-300': activeSection === section.id,
                'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-dark-800 hover:text-gray-900 dark:hover:text-gray-100': activeSection !== section.id
              }
            ]"
          >
            <component :is="section.icon" class="w-5 h-5 mr-3" />
            {{ section.name }}
          </button>
        </nav>
      </div>

      <!-- Settings content -->
      <div class="lg:col-span-2 overflow-y-auto">
        <!-- Theme Settings -->
        <div v-if="activeSection === 'theme'" class="card">
          <div class="p-6">
            <h2 class="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-6">
              主题设置
            </h2>

            <!-- Theme mode -->
            <div class="space-y-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                  主题模式
                </label>
                <div class="grid grid-cols-3 gap-3">
                  <button
                    v-for="mode in themeModes"
                    :key="mode.value"
                    @click="themeStore.setMode(mode.value)"
                    :class="[
                      'p-4 rounded-lg border-2 transition-all duration-200 text-left',
                      {
                        'border-primary-500 bg-primary-50 dark:bg-primary-900/20': themeStore.mode === mode.value,
                        'border-gray-200 dark:border-dark-600 hover:border-gray-300 dark:hover:border-dark-500': themeStore.mode !== mode.value
                      }
                    ]"
                  >
                    <component :is="mode.icon" class="w-6 h-6 mb-2 text-gray-600 dark:text-gray-400" />
                    <div class="text-sm font-medium text-gray-900 dark:text-gray-100">
                      {{ mode.label }}
                    </div>
                    <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                      {{ mode.description }}
                    </div>
                  </button>
                </div>
              </div>

              <!-- 移除自定义颜色选择器，使用预设配色 -->

              <!-- Theme presets -->
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                  配色主题
                </label>
                <p class="text-sm text-gray-600 dark:text-gray-400 mb-4">
                  选择您喜欢的配色方案，配色主题不会影响明暗模式设置
                </p>
                <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
                  <button
                    v-for="(preset, key) in themeStore.presets"
                    :key="key"
                    @click="themeStore.applyPreset(key as keyof typeof themeStore.presets)"
                    :class="[
                      'p-3 rounded-lg border transition-all duration-200 text-left hover:shadow-md',
                      isCurrentPreset(preset) ? 
                        'border-primary-500 bg-primary-50 dark:bg-primary-900/20 ring-2 ring-primary-500/20' :
                        'border-gray-200 dark:border-dark-600 hover:border-primary-300 dark:hover:border-primary-600'
                    ]"
                  >
                    <div class="flex items-center space-x-2 mb-2">
                      <div 
                        class="w-5 h-5 rounded-full border-2 border-white dark:border-gray-800 shadow-sm"
                        :style="{ backgroundColor: preset.primaryColor }"
                      ></div>
                      <div 
                        class="w-5 h-5 rounded-full border-2 border-white dark:border-gray-800 shadow-sm"
                        :style="{ backgroundColor: preset.accentColor }"
                      ></div>
                    </div>
                    <div class="text-sm font-medium text-gray-900 dark:text-gray-100 capitalize mb-1">
                      {{ key === 'default' ? '默认' : 
                          key === 'ocean' ? '海洋' :
                          key === 'forest' ? '森林' :
                          key === 'sunset' ? '日落' :
                          key === 'minimal' ? '简约' :
                          key === 'purple' ? '紫色' :
                          key === 'rose' ? '玫瑰' :
                          key === 'amber' ? '琥珀' :
                          key === 'indigo' ? '靛蓝' :
                          key === 'teal' ? '青色' :
                          key === 'slate' ? '石板' :
                          key === 'emerald' ? '翡翠' : key }}
                    </div>
                    <div v-if="isCurrentPreset(preset)" class="text-xs text-primary-600 dark:text-primary-400">
                      ✓ 当前使用
                    </div>
                    <div v-else class="text-xs text-gray-500 dark:text-gray-400">
                      点击应用
                    </div>
                  </button>
                </div>
              </div>

              <!-- AI theme suggestions -->
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                  AI智能推荐
                </label>
                <div class="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                  <div class="flex items-start space-x-3">
                  
                    <div>
                      <p class="text-sm font-medium text-blue-900 dark:text-blue-100">
                        智能主题建议
                      </p>
                      <p class="text-sm text-blue-700 dark:text-blue-300 mt-1">
                        根据您的使用习惯和时间，AI会自动推荐最适合的主题配置。
                      </p>
                      <button
                        @click="getAIThemeRecommendation"
                        class="mt-3 btn-primary text-xs flex justify-center"
                        :disabled="loading"
                      >
                        <SparklesIcon class="w-4 h-4 mr-1" />
                        获取推荐
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Account Settings -->
        <div v-if="activeSection === 'account'" class="card">
          <div class="p-6">
            <h2 class="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-6">
              账户设置
            </h2>

            <form @submit.prevent="updateProfile" class="space-y-6">
              <!-- Profile info -->
              <div class="flex items-center space-x-6">
                <div class="flex-shrink-0">
                  <div class="w-16 h-16 bg-primary-500 rounded-full flex items-center justify-center">
                    <span class="text-white font-medium text-xl">
                      {{ authStore.user?.name?.charAt(0) || 'U' }}
                    </span>
                  </div>
                </div>
                <div class="flex-1">
                  <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                    {{ authStore.user?.name }}
                  </h3>
                  <p class="text-gray-500 dark:text-gray-400">
                    {{ authStore.user?.email }}
                  </p>
                  <p class="text-sm text-gray-400 dark:text-gray-500">
                    角色：{{ authStore.user?.role }}
                  </p>
                </div>
              </div>

              <!-- Form fields -->
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    用户名
                  </label>
                  <input
                    v-model="profileForm.username"
                    type="text"
                    class="input-primary"
                    disabled
                  />
                </div>

                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    邮箱
                  </label>
                  <input
                    v-model="profileForm.email"
                    type="email"
                    class="input-primary"
                  />
                </div>

                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    姓名
                  </label>
                  <input
                    v-model="profileForm.name"
                    type="text"
                    class="input-primary"
                  />
                </div>

                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    角色
                  </label>
                  <input
                    v-model="profileForm.role"
                    type="text"
                    class="input-primary"
                    disabled
                  />
                </div>
              </div>

              <div class="flex justify-end">
                <button
                  type="submit"
                  class="btn-primary"
                  :disabled="loading"
                >
                  保存更改
                </button>
              </div>
            </form>

            <!-- Change password -->
            <div class="mt-8 pt-8 border-t border-gray-200 dark:border-dark-700">
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4">
                修改密码
              </h3>
              
              <form @submit.prevent="changePassword" class="space-y-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    当前密码
                  </label>
                  <input
                    v-model="passwordForm.oldPassword"
                    type="password"
                    class="input-primary"
                    required
                  />
                </div>

                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    新密码
                  </label>
                  <input
                    v-model="passwordForm.newPassword"
                    type="password"
                    class="input-primary"
                    required
                    minlength="6"
                  />
                </div>

                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    确认新密码
                  </label>
                  <input
                    v-model="passwordForm.confirmPassword"
                    type="password"
                    class="input-primary"
                    required
                  />
                </div>

                <div class="flex justify-end">
                  <button
                    type="submit"
                    class="btn-secondary"
                    :disabled="loading || passwordForm.newPassword !== passwordForm.confirmPassword"
                  >
                    修改密码
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>

        <!-- Notifications Settings -->
        <div v-if="activeSection === 'notifications'" class="card">
          <div class="p-6">
            <h2 class="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-6">
              通知设置
            </h2>

            <div class="space-y-6">
              <!-- Notification preferences -->
              <div v-for="setting in notificationSettings" :key="setting.id">
                <div class="flex items-center justify-between">
                  <div>
                    <h3 class="text-sm font-medium text-gray-900 dark:text-gray-100">
                      {{ setting.title }}
                    </h3>
                    <p class="text-sm text-gray-500 dark:text-gray-400">
                      {{ setting.description }}
                    </p>
                  </div>
                  <label class="relative inline-flex items-center cursor-pointer">
                    <input
                      v-model="setting.enabled"
                      type="checkbox"
                      class="sr-only peer"
                      @change="updateNotificationSetting(setting)"
                    />
                    <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 dark:peer-focus:ring-primary-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-primary-600"></div>
                  </label>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- System Settings -->
        <div v-if="activeSection === 'system'" class="card">
          <div class="p-6">
            <h2 class="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-6">
              系统设置
            </h2>

            <div class="space-y-6">
              <!-- System info -->
              <div>
                <h3 class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-3">
                  系统信息
                </h3>
                <div class="bg-gray-50 dark:bg-dark-800 rounded-lg p-4 space-y-2">
                  <div class="flex justify-between text-sm">
                    <span class="text-gray-500 dark:text-gray-400">版本</span>
                    <span class="text-gray-900 dark:text-gray-100">{{ appStore.appInfo.version }}</span>
                  </div>
                  <div class="flex justify-between text-sm">
                    <span class="text-gray-500 dark:text-gray-400">连接状态</span>
                    <span :class="appStore.isOnline ? 'text-green-600' : 'text-red-600'">
                      {{ appStore.isOnline ? '在线' : '离线' }}
                    </span>
                  </div>
                  <div class="flex justify-between text-sm">
                    <span class="text-gray-500 dark:text-gray-400">内存使用</span>
                    <span class="text-gray-900 dark:text-gray-100">
                      {{ appStore.performanceMetrics.memoryUsage }}MB
                    </span>
                  </div>
                </div>
              </div>

              <!-- Data management -->
              <div>
                <h3 class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-3">
                  数据管理
                </h3>
                <div class="space-y-3">
                  <button
                    @click="clearCache"
                    class="w-full flex items-center justify-between p-3 text-left rounded-lg border border-gray-200 dark:border-dark-600 hover:border-yellow-500 dark:hover:border-yellow-400 transition-colors"
                  >
                    <div>
                      <div class="text-sm font-medium text-gray-900 dark:text-gray-100">
                        清除缓存
                      </div>
                      <div class="text-xs text-gray-500 dark:text-gray-400">
                        清除浏览器缓存数据
                      </div>
                    </div>
                    <TrashIcon class="w-5 h-5 text-yellow-500" />
                  </button>

                  <button
                    @click="clearAllData"
                    class="w-full flex items-center justify-between p-3 text-left rounded-lg border border-gray-200 dark:border-dark-600 hover:border-red-500 dark:hover:border-red-400 transition-colors"
                  >
                    <div>
                      <div class="text-sm font-medium text-gray-900 dark:text-gray-100">
                        清除所有数据
                      </div>
                      <div class="text-xs text-gray-500 dark:text-gray-400">
                        清除所有本地存储数据（危险操作）
                      </div>
                    </div>
                    <ExclamationTriangleIcon class="w-5 h-5 text-red-500" />
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useAuthStore } from '@/store/auth'
import { useAppStore } from '@/store/app'
import { useThemeStore } from '@/store/theme'
import type { ThemeMode } from '@/types'

// Icons
import {
  SwatchIcon,
  UserIcon,
  BellIcon,
  CogIcon,
  SunIcon,
  MoonIcon,
  ComputerDesktopIcon,
  SparklesIcon,
  TrashIcon,
  ExclamationTriangleIcon
} from '@heroicons/vue/24/outline'

const authStore = useAuthStore()
const appStore = useAppStore()
const themeStore = useThemeStore()

// State
const activeSection = ref('theme')
const loading = ref(false)

// Settings sections
const sections = [
  { id: 'theme', name: '主题外观', icon: SwatchIcon },
  { id: 'account', name: '账户设置', icon: UserIcon },
  { id: 'notifications', name: '通知设置', icon: BellIcon },
  { id: 'system', name: '系统设置', icon: CogIcon }
]

// Theme modes
const themeModes = [
  {
    value: 'light' as ThemeMode,
    label: '亮色模式',
    description: '适合白天使用',
    icon: SunIcon
  },
  {
    value: 'dark' as ThemeMode,
    label: '暗色模式',
    description: '适合夜间使用',
    icon: MoonIcon
  },
  {
    value: 'auto' as ThemeMode,
    label: '自动模式',
    description: '跟随系统设置',
    icon: ComputerDesktopIcon
  }
]

// Forms
const profileForm = reactive({
  username: '',
  email: '',
  name: '',
  role: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// Notification settings
const notificationSettings = ref([
  {
    id: 'ai_responses',
    title: 'AI响应通知',
    description: '当AI完成回复时显示通知',
    enabled: true
  },
  {
    id: 'system_alerts',
    title: '系统警告',
    description: '接收系统错误和警告通知',
    enabled: true
  },
  {
    id: 'data_updates',
    title: '数据更新',
    description: '数据变更时发送通知',
    enabled: false
  },
  {
    id: 'theme_suggestions',
    title: 'AI主题建议',
    description: '接收AI的主题切换建议',
    enabled: true
  }
])

// Methods
const updateProfile = async () => {
  loading.value = true
  try {
    // Update user profile logic here
    authStore.updateUserProfile(profileForm)
    appStore.showSuccess('个人信息已更新')
  } catch (error) {
    appStore.showError('更新失败')
  } finally {
    loading.value = false
  }
}

const changePassword = async () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    appStore.showError('新密码确认不一致')
    return
  }

  loading.value = true
  try {
    const result = await authStore.changePassword(
      passwordForm.oldPassword,
      passwordForm.newPassword
    )
    
    if (result.success) {
      appStore.showSuccess('密码已更改')
      // Clear form
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } else {
      appStore.showError(result.message)
    }
  } catch (error) {
    appStore.showError('密码更改失败')
  } finally {
    loading.value = false
  }
}

const updateNotificationSetting = (setting: any) => {
  // Save to local storage
  localStorage.setItem(`notification_${setting.id}`, setting.enabled.toString())
  appStore.showSuccess(`${setting.title}设置已更新`)
}

const getAIThemeRecommendation = () => {
  loading.value = true
  
  // Simulate AI analysis
  setTimeout(() => {
    const hour = new Date().getHours()
    let recommendation = ''
    let suggestedTheme = themeStore.mode
    
    if (hour >= 6 && hour < 18) {
      if (themeStore.isDark) {
        recommendation = '基于您当前的使用时间（白天），建议使用亮色主题以获得更好的视觉体验和工作效率。'
        suggestedTheme = 'light'
      } else {
        recommendation = '您当前的亮色主题很适合白天工作，有助于提高注意力和减少眼部疲劳。'
      }
    } else {
      if (themeStore.isLight) {
        recommendation = '基于您当前的使用时间（夜间），建议使用暗色主题以减少蓝光刺激，保护视力。'
        suggestedTheme = 'dark'
      } else {
        recommendation = '您当前的暗色主题很适合夜间使用，有助于减少眼部疲劳和改善睡眠质量。'
      }
    }
    
    appStore.showInfo(recommendation)
    
    if (suggestedTheme !== themeStore.mode) {
      setTimeout(() => {
        if (confirm('是否应用AI推荐的主题设置？')) {
          themeStore.setMode(suggestedTheme)
          appStore.showSuccess('主题已按AI建议更新')
        }
      }, 3000)
    }
    
    loading.value = false
  }, 2000)
}

const clearCache = () => {
  if (confirm('确定要清除浏览器缓存吗？这将删除临时数据但保留您的设置。')) {
    // Clear various caches
    if ('caches' in window) {
      caches.keys().then(names => {
        names.forEach(name => {
          caches.delete(name)
        })
      })
    }
    
    appStore.showSuccess('缓存已清除')
  }
}

const clearAllData = () => {
  if (confirm('⚠️ 危险操作：这将清除所有本地数据，包括登录状态、设置和对话历史。确定要继续吗？')) {
    if (confirm('最后确认：此操作不可撤销，您需要重新登录。')) {
      // Clear all local storage
      localStorage.clear()
      sessionStorage.clear()
      
      // Clear IndexedDB if used
      if ('indexedDB' in window) {
        // Implementation depends on specific usage
      }
      
      appStore.showWarning('所有数据已清除，即将重新加载页面')
      
      setTimeout(() => {
        window.location.reload()
      }, 2000)
    }
  }
}

const isCurrentPreset = (preset: any) => {
  return preset.primaryColor === themeStore.config.primaryColor &&
         preset.accentColor === themeStore.config.accentColor
}



// Lifecycle
onMounted(() => {
  // Initialize forms with user data
  if (authStore.user) {
    profileForm.username = authStore.user.username
    profileForm.email = authStore.user.email || ''
    profileForm.name = authStore.user.name
    profileForm.role = authStore.user.role
  }
  
  // Load notification settings
  notificationSettings.value.forEach(setting => {
    const saved = localStorage.getItem(`notification_${setting.id}`)
    if (saved !== null) {
      setting.enabled = saved === 'true'
    }
  })
})
</script>

<style scoped>
/* Custom toggle switch styles are handled by Tailwind classes */
</style>
